import { createStore } from 'vuex'

type CtpState = {
  jwt: string|null
  info: any|null
  power: number|null
}

const LOG_NEW_JWT = "LOG_NEW_JWT",
      LOG_NEW_INFO = "LOG_NEW_INFO",
      LOG_NEW_POWER = "LOG_NEW_POWER",
      CLEAR_JWT = "CLEAR_JWT",
      CLEAR_INFO = "CLEAR_INFO",
      CLEAR_POWER = "CLEAR_POWER"
  
export default createStore<CtpState>({
  state: {
    jwt: null,
    info: null,
    power: null
  },
  getters: {
    jwt: function(state) {
      return state.jwt
    },
    info: function(state) {
      return state.info
    },
    power: function(state) {
      return state.power
    },
  },
  mutations: {
    LOG_NEW_JWT: (state, newVal) => {
      state.jwt = newVal
    },
    LOG_NEW_INFO: (state, newVal) => {
      state.info = newVal
    },
    LOG_NEW_POWER: (state, newVal) => {
      state.power = newVal
    },
    CLEAR_JWT: (state) => {
      state.jwt = null
    },
    CLEAR_INFO: (state) => {
      state.info = null
    },
    CLEAR_POWER: (state) => {
      state.power = null
    }
  },
  actions: {
    changeLoginStatus: ({ commit, state }, payload:{claims:any, jwt:string}|null) => {
      if (payload != null) {
        commit(LOG_NEW_INFO, payload.claims)
        commit(LOG_NEW_JWT, payload.jwt)
        commit(LOG_NEW_POWER, 0)
        return
      }
      commit(CLEAR_JWT)
      commit(CLEAR_INFO)
      commit(CLEAR_POWER)
    }
  },
  modules: {
  }
})

// dispatch -> actions
// commit -> mutations
// TODO 拆分结构